import tkinter as tk
from tkinter import messagebox, filedialog
from PIL import Image, ImageTk
import os
from src.core.item_manager import edit_item
from src.storage.file_manager import save_to_file
from shutil import copy2

LIGHT_PINK = "#FFD1DC"
LIGHT_BROWN = "#E7BD6E"
LIGHT_BROWN_ACTIVE = "#D4A76A"
DARK_BROWN = "#6B4832"

def init_edit_screen(parent, items, pet_id):
    """Initialize pet edit screen"""
    pet_to_edit = None
    for pet in items:
        if pet['id'] == pet_id:
            pet_to_edit = pet
            break
    
    if not pet_to_edit:
        messagebox.showerror("Error", f"Pet with ID {pet_id} not found")
        from src.ui.tkinter.main_window import show_screen
        show_screen("selection")
        return None
    
    for widget in parent.winfo_children():
        widget.destroy()
    
    main_frame = tk.Frame(parent, bg=LIGHT_PINK)
    main_frame.pack(fill=tk.BOTH, expand=True, padx=10, pady=10)
    
    tk.Label(
        main_frame,
        text="Edit Pet Information",
        font=("SimHei", 16, "bold"),
        bg=LIGHT_PINK,
        fg=DARK_BROWN
    ).pack(pady=20)
    
    id_frame = tk.Frame(main_frame, bg=LIGHT_PINK)
    id_frame.pack(fill=tk.X, pady=5)
    tk.Label(id_frame, text="ID:", font=("SimHei", 12), bg=LIGHT_PINK, fg=DARK_BROWN).pack(side=tk.LEFT, padx=5)
    tk.Label(id_frame, text=pet_to_edit['id'], font=("SimHei", 12), bg=LIGHT_PINK, fg=DARK_BROWN).pack(side=tk.LEFT, padx=5)
    
    name_frame = tk.Frame(main_frame, bg=LIGHT_PINK)
    name_frame.pack(fill=tk.X, pady=5)
    tk.Label(name_frame, text="Name:", font=("SimHei", 12), bg=LIGHT_PINK, fg=DARK_BROWN).pack(side=tk.LEFT, padx=5)
    name_entry = tk.Entry(name_frame, font=("SimHei", 12))
    name_entry.insert(0, pet_to_edit['name'])
    name_entry.pack(side=tk.LEFT, fill=tk.X, expand=True, padx=5)
    
    type_frame = tk.Frame(main_frame, bg=LIGHT_PINK)
    type_frame.pack(fill=tk.X, pady=5)
    tk.Label(type_frame, text="Type(Warrior,Assassin,Mage,Marksman,Support):", font=("SimHei", 12), bg=LIGHT_PINK, fg=DARK_BROWN).pack(side=tk.LEFT, padx=5)
    type_entry = tk.Entry(type_frame, font=("SimHei", 12))
    type_entry.insert(0, pet_to_edit['item_type'])
    type_entry.pack(side=tk.LEFT, fill=tk.X, expand=True, padx=5)
    
    age_frame = tk.Frame(main_frame, bg=LIGHT_PINK)
    age_frame.pack(fill=tk.X, pady=5)
    tk.Label(age_frame, text="Age:", font=("SimHei", 12), bg=LIGHT_PINK, fg=DARK_BROWN).pack(side=tk.LEFT, padx=5)
    age_entry = tk.Entry(age_frame, font=("SimHei", 12))
    age_entry.insert(0, pet_to_edit['age'])
    age_entry.pack(side=tk.LEFT, fill=tk.X, expand=True, padx=5)
    
    img_frame = tk.Frame(main_frame, bg=LIGHT_PINK)
    img_frame.pack(fill=tk.X, pady=15)
    tk.Label(img_frame, text="Pet Image:", font=("SimHei", 12), bg=LIGHT_PINK, fg=DARK_BROWN).pack(side=tk.LEFT, padx=5)
    
    selected_img_path = [pet_to_edit.get('image_path')]
    
    preview_frame = tk.Frame(img_frame, bg=LIGHT_PINK)
    preview_frame.pack(side=tk.LEFT, padx=10)
    
    preview_label = tk.Label(preview_frame, text="No image", width=30, height=10, relief="solid", bg="white", fg=DARK_BROWN, font=("SimHei", 10))
    preview_label.pack()
    
    if selected_img_path[0] and os.path.exists(selected_img_path[0]):
        try:
            img = Image.open(selected_img_path[0])
            img.thumbnail((100, 100))
            photo = ImageTk.PhotoImage(img)
            preview_label.config(image=photo, text="", bg=LIGHT_PINK)
            preview_label.image = photo
        except Exception as e:
            print(f"Failed to load existing image: {str(e)}")
    
    def browse_image():
        """
        Opens file dialog to select a pet image, displays a resized preview.
    
        Stores selected path, resizes image to 100x100 thumbnail, and updates preview.
        Shows error and resets selection if image loading fails.
        """
        file_path = filedialog.askopenfilename(
            title="Select Pet Image",
            filetypes=[("Image files", "*.jpg *.jpeg *.png *.gif *.bmp")]
        )
        if file_path:
            selected_img_path[0] = file_path
            try:
                img = Image.open(file_path)
                img.thumbnail((100, 100))
                photo = ImageTk.PhotoImage(img)
                preview_label.config(image=photo, text="", bg=LIGHT_PINK)
                preview_label.image = photo
            except Exception as e:
                messagebox.showerror("Error", f"Failed to load image: {str(e)}")
                selected_img_path[0] = None
    
    def clear_image():
        """Clears selected image path and resets preview to "No image"."""
        selected_img_path[0] = None
        preview_label.config(image="", text="No image")
    
    browse_btn = tk.Button(img_frame, text="Browse Image", command=browse_image,
                          bg=LIGHT_BROWN, fg=DARK_BROWN, font=("SimHei", 10, "bold"),
                          relief="solid", borderwidth=1, activebackground=LIGHT_BROWN_ACTIVE)
    browse_btn.pack(side=tk.LEFT, padx=5)
    
    clear_btn = tk.Button(img_frame, text="Clear Image", command=clear_image,
                         bg=LIGHT_BROWN, fg=DARK_BROWN, font=("SimHei", 10, "bold"),
                         relief="solid", borderwidth=1, activebackground=LIGHT_BROWN_ACTIVE)
    clear_btn.pack(side=tk.LEFT, padx=5)
    
    def save_changes():
        """
        Saves edited pet information after validation.
    
        Validates input, processes image (if any), updates pet data,
        saves to JSON file, and provides user feedback. Returns to
        selection screen on success.
        """
        new_name = name_entry.get().strip()
        new_type = type_entry.get().strip()
        new_age_str = age_entry.get().strip()
        
        if not new_name or not new_type:
            messagebox.showerror("Error", "Name and type cannot be empty")
            return None
        
        try:
            new_age = int(new_age_str)
            if new_age < 1:
                raise ValueError("Age must be greater than 0.")
        except ValueError as e:
            messagebox.showerror("Error", f"Age format error: {str(e)}")
            return None
        
        saved_img_path = None
        if selected_img_path[0]:
            try:
                tkinter_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
                pet_images_dir = os.path.join(tkinter_dir, "pet_images")
                if not os.path.exists(pet_images_dir):
                    os.makedirs(pet_images_dir)
                
                img_extension = os.path.splitext(selected_img_path[0])[1]
                saved_img_path = os.path.join(pet_images_dir, f"pet_{pet_id}{img_extension}")
                
                copy2(selected_img_path[0], saved_img_path)
            except Exception as e:
                messagebox.showerror("Error", f"Failed to save image: {str(e)}")
                return None
        elif selected_img_path[0] == "":
            saved_img_path = ""
        
        success, msg = edit_item(
            items=items,
            item_id=pet_id,
            new_name=new_name,
            new_item_type=new_type,
            new_age=new_age,
            new_image_path=saved_img_path
        )
        
        if success:
            save_to_file(items, "pets.json")
            messagebox.showinfo("Success", msg)
            back_to_selection(parent)
        else:
            messagebox.showerror("Error", msg)
    
    btn_frame = tk.Frame(main_frame, bg=LIGHT_PINK)
    btn_frame.pack(pady=20)
    
    save_btn = tk.Button(btn_frame, text="Save Changes", command=save_changes, width=15,
                       bg=LIGHT_BROWN, fg=DARK_BROWN, font=("SimHei", 10, "bold"),
                       relief="solid", borderwidth=1, activebackground=LIGHT_BROWN_ACTIVE)
    save_btn.pack(side=tk.LEFT, padx=10)
    
    cancel_btn = tk.Button(btn_frame, text="Cancel", command=lambda: back_to_selection(parent), width=15,
                         bg=LIGHT_BROWN, fg=DARK_BROWN, font=("SimHei", 10, "bold"),
                         relief="solid", borderwidth=1, activebackground=LIGHT_BROWN_ACTIVE)
    cancel_btn.pack(side=tk.LEFT, padx=10)

def back_to_selection(parent):
    """Return to selection screen"""
    from src.ui.tkinter.main_window import show_screen
    show_screen("selection")
    return None